const mongoose = require("mongoose");
var Category = require('../models/category.model');
var New = require('../models/news.model');

//增加
exports.create = function(req, res, next) {
    const category = new Category(req.body);
    category.save().then((data) => res.json(data));
}


//更改
exports.update = function(req, res, next) {
    var id = req.params.id;
    Category.findByIdAndUpdate(id, { $set: req.body }, { new: false, upsert: false }).then((data) => res.json(data));
}

//删除
exports.remove = function(req, res, next) {
        Category.find({ parentId: req.params.id },async function(err, doc) {

            var str = [];
            str.push(req.params.id);
            for (var i in doc) {
                str.push(doc[i]._id);
            }
           /* New.find({ newsId:{$in:str}}).then(data=>{

              // console.log(data);
               var result=[];
               data.map((value,index)=>{
                   result.push(value._id);
               })
               console.log(result);

           }); */


            if (str.length > 0) {
                Category.remove({ _id: { $in: str } }).then(data => {
                    //res.json({ "message": "数据已成功删除!" });
                    New.find({ newsId:{$in:str}}).then(data=>{

                         var result=[];
                         data.map((value,index)=>{
                             result.push(value._id);
                         })
                        // console.log(result);
                          New.remove({_id:{$in:result}}).then(data=>{
                             res.json({"message":"数据已经成功删除"});
                         })
                     });
                })

            }
        })


    }
    //让数据变成树形
function datatree(data, pid) {
    var result = [],
        temp;
    var data = JSON.parse(JSON.stringify(data));
    for (var i in data) {
        if (data[i].parentId === pid) {
            result.push(data[i]);
            temp = datatree(data, data[i]._id);
            if (temp.length > 0) {
                data[i].children = temp;
            }
        }
    }
    return result;
}


exports.list = function(req, res, next) {
    var type = req.params.type;
    Category.find({ type: type }, function(err, data) {
        res.json(datatree(data, null));
    })
}

//根据id查找
exports.selectbyId = function(req, res, next) {
    var id = req.params.id;
    Category.findById(id).then((data) => res.json(data));
}

exports.allList=function(req,res,next){
    Category.find({parentId:null},function(err,data){
        //console.log(data);
        res.json(data);
    })
}